package downloader

import (
	"crypto/md5"
	"encoding/hex"
	"math/rand"
	"os"
	"strconv"
	"time"
)

func isFileExists(savepath string) bool {
	if _, err := os.Stat(savepath); os.IsNotExist(err) {
		return false
	} else {
		return true
	}
}
func getFileMd5(filebyte []byte) (name string, err error) { //目测是16位md5
	filemd5byte16 := md5.Sum(filebyte)
	tmp := make([]byte, 16)
	for _, value := range filemd5byte16 {
		tmp = append(tmp, value)
	}
	return hex.EncodeToString(tmp[16:]), nil
}
func getRandString(slen int) string {
	var t string = ""
	for i := 1; i <= slen; i++ {
		t = t + strconv.Itoa(rand.New(rand.NewSource(time.Now().UnixNano())).Intn(10))
	}
	return t
}
func isDirExists(path string) bool {
	fi, err := os.Stat(path)
	if err != nil {
		return os.IsExist(err)
	} else {
		return fi.IsDir()
	}
}
func save(filebyte []byte, savepath string) (err error) {
	if !isFileExists(savepath) {
		f, err := os.OpenFile(savepath, os.O_CREATE, 0660)
		if err != nil {
			return err
		}
		_, err = f.Write(filebyte)
		f.Close()
		if err != nil {
			return err
		}
	}
	return nil
}
